import React, { useEffect, useState } from 'react'
import { Menu } from "antd"
import menusData from "@/config/menusData"
import {useDispatch,useSelector} from "react-redux"

export default function MuMenu() {
    //数据初始化，考虑页面第一次渲染的情况
    const [userInfo, setUserInfo] = useState({role:{}})
    const dispatch = useDispatch()
    const {menuRD:{menus}} = useSelector((state)=>{
        return state
    })
    useEffect(() => {
        const userInfo = JSON.parse(localStorage.userInfo || "{}")
        setUserInfo(userInfo)
        console.log(userInfo);
    }, [])

    const deepMenus = (array,news=[]) => {
        const {menus} = userInfo.role
        /**
         * 第一次调用deepMenus:menusData news=[]
         * news = [{首页},{用户},{角色},{店铺},{商品管理,children:[]}]
         * 遇到有二级菜单，还是会将二级菜单，push
         * 第二次调用deepMenus：[商品列表， 商品分类]，news=[]
         * news=[商品列表,商品分类]
         * return news 赋值给商品管理：children
         * 第三次调用deepMenus
         * 
         * 
         */
        for (const item of array) {
            if(menus && menus.includes(item.key)){
                if(!item.children){
                    news.push(item)
                }else{
                    let node = {...item,children:[]}
                    news.push(node)
                    //这个函数调用得到一个结果 [商品列表,商品分类]
                    deepMenus(item.children,node.children)
                }
            }
        }
        return news;
    }

    const changeMenuItem = ({ item, key, keyPath, domEvent })=>{
        ///home/user
        console.log(key);
        //domEvent 对象
        const text = domEvent.target.innerText;
        const obj = {id:Date.now(),name:text,path:key,state:1}
        dispatch({
            type:"ADDMENUS",
            payload:obj
        })
    }

    return (
        // 给Menu添加一个onClick，实际上点击Menu.Item触发
        <Menu
            theme="dark"
            // defaultSelectedKeys={['/home/user']}
            mode="inline"
            onClick={changeMenuItem}
            items={deepMenus(menusData)}
        />
    )
}
